//
//  HMStatusPictureView.swift
//  Weibo
//
//  Created by 米易雅克 on 16/4/19.
//  Copyright © 2016年 米易雅克. All rights reserved.
//

import UIKit
import SDWebImage
//colloectionViewCell的间距
private let HMStatusPictureViewCellMargin: CGFloat = 4

//cell的最大列数 3列
private let HMStatusPictureMaxColumn = 3

//cell的宽和高
private let HMStatusPictureViewItemWH = (UIScreen.mainScreen().bounds.width - 2 * HMStatusCellMargin - (CGFloat(HMStatusPictureMaxColumn - 1) * HMStatusPictureViewCellMargin)) / CGFloat(HMStatusPictureMaxColumn)


//微博配图
class HMStatusPictureView: UICollectionView {
    
    private let ReuseIdentifier = "ReuseIdentifier"
    
    //微博配图url数组
    var pictureURLs: [NSURL]? {
    
        didSet {
        // 当别人设置配图的url后,我们就来计算配图的高度
            let size = calcViewSize()
            
        // 自己来约束大小,当cell给pictureURLs之后计算出宽高,然后重新修改约束
            self.snp_updateConstraints { (make) in
                
                make.size.equalTo(size)
            }
//            HMPrint("配图、\(pictureURLs)")
            self.reloadData()
        }
    
    }
    
    //计算配图宽高
    private func calcViewSize() -> CGSize {
    
    layout.itemSize = CGSize(width: HMStatusPictureViewItemWH, height: HMStatusPictureViewItemWH)
    layout.minimumLineSpacing = 0
    layout.minimumInteritemSpacing = 0
        
    //判断图片数量
        let count = pictureURLs?.count ?? 0
        if count == 0 {
            HMPrint("没有图片")
            return CGSizeZero
        }
        
    //只有一张图片
        if count == 1 {
            //默认大小
            var size = CGSize(width: HMStatusPictureViewItemWH, height: HMStatusPictureViewItemWH)
            
            //根据图片大小来设置
            let url = pictureURLs?.first!
            //如果缓存没有图片
            if let image = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(url?.absoluteString) {
                // 点坐标:像素 / 2, 在 SDWebimage 3.7.3以后
                size = image.size
                size = CGSize(width: size.width * UIScreen.mainScreen().scale, height: size.height * UIScreen.mainScreen().scale)
            }
            if size.width < 40 {
                size.width = 40
            }
            let screenWidth = UIScreen.mainScreen().bounds.width
            
            if size.width > screenWidth {
                size.width = screenWidth * 0.5
            }
            
            layout.itemSize = size
            return size
        }
        layout.minimumInteritemSpacing = HMStatusPictureViewCellMargin
        layout.minimumLineSpacing = HMStatusPictureViewCellMargin
        
    //多张图片
        var column = HMStatusPictureMaxColumn
        if count == 2 || count == 4 {
            column = 2
        }
    // 服务器开发用得比较多,分页,保证列数是整数
    // 行数 = (总个数 + 列数 - 1) / 列数
        let row = (count + column - 1) / column
        
    //计算宽高
    // 宽度 = 列数 * item宽度 + (列数 - 1) * 列间距
        let width = CGFloat(column) * HMStatusPictureViewItemWH + (CGFloat(column) - 1) * HMStatusPictureViewCellMargin
    //高度 = 行数 * item高度 + (行数 - 1) * 行间距
        let height = CGFloat(row) * HMStatusPictureViewItemWH + (CGFloat(row) - 1) * HMStatusPictureViewCellMargin
        
        return CGSize(width: width, height: height)
        
        
    }

    private var layout = UICollectionViewFlowLayout()
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    init() {
    
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        //设置数据源
        self.dataSource = self
        //注册cell
        self.registerClass(HMStatusPictureViewCell.self, forCellWithReuseIdentifier: ReuseIdentifier)
        
    }
    
    
}


//MARK: 扩展实现数据
extension HMStatusPictureView: UICollectionViewDataSource {

    //返回cell个数
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictureURLs?.count ?? 0
    }
    //返回cell
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ReuseIdentifier, forIndexPath: indexPath) as! HMStatusPictureViewCell
        
        cell.imageURL = pictureURLs![indexPath.item]
        
        return cell
    }

}

//MARK:自定义cell
class HMStatusPictureViewCell: UICollectionViewCell {

    // 每个cell需要一个图片的URL来取下载图片
    /// didSet是存储性数性才有的
    var imageURL: NSURL? {
        didSet {
        
            bkgImageView.sd_setImageWithURL(imageURL!)
        
        }
    
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        prepareUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func prepareUI() {
    
    contentView.addSubview(bkgImageView)
    bkgImageView.snp_makeConstraints { (make) in
        make.edges.equalTo(contentView)
        
        }
    }
//MARK: 懒加载
    //背景图片
    private lazy var bkgImageView: UIImageView = UIImageView()
}